<template>
  <div class="defect-line-chart" ref="trendChart"></div>
</template>
<script>
import * as echarts from "echarts"
export const lineColors=[
  '#99D115',
  '#FFAA00',
  '#13AFBA',
  '#5A1CEB',
  '#EB2F93',
  '#00C25B'
]
export const barColors=[
  '#9EAEFF',
  '#5CAEFF',
  '#99D115',
  '#FFAA00',
  '#13AFBA',
  '#5A1CEB',
  '#EB2F93',
  '#00C25B'
]
export default {
  computed:{
    isDefectPoint(){
      //不良点位和其他不一样
      return this.detailData.alarmType === 'DefectPoint'
    },
    stage() {
      let factory = this.detailData.sourceFactory||this.detailData.factory
      return [
        {factory:'ARRAY',stage:'array'},
        {factory:'CELL',stage:'cell'},
        {factory:'MODULE',stage:'module'}
      ].find(item=>item.factory===factory)
    },
  },
  data() {
    return {
      detailData:{}
    }
  },
  methods: {
    formatTrendData (keys, dataObject) {
      return keys.map(key => {
        const value = dataObject[key];
        return value === undefined ? "" : value;
      });
    },
    formatTrendRatioData (keys, dataObject) {
      return keys.map(key => {
        const value = dataObject[key];
        return value === undefined ? "" : value.toFixed(2);
      });
    },
    genSeriesBarName(stage){
      let name =""
      if (stage === 'array') {
        name = `Array 投入的Panel数量`
      } else {
        name = stage === 'module'
            ? 'MDL投入的Panel数量'
            : 'CT投入的Panel数量'
      }
      return name
    },
    setTrendChartData({year, quarter, month, week, day, rightValues},chartTit) {
      let yearKeys = Object.keys(year);
      let quarterKeys = Object.keys(quarter);
      let monthKeys = Object.keys(month);
      let weekKeys = Object.keys(week);
      let dayKeys = Object.keys(day);
      let xAxisData = [...yearKeys, "", ...quarterKeys, "", ...monthKeys, "", ...weekKeys, "", ...dayKeys]
      let tempArr = []
      let  ratioConfigs = [
        {key: 'yearRatio', keys: yearKeys, addSeparator: true},
        {key: 'quarterRatio', keys: quarterKeys, addSeparator: true},
        {key: 'monthRatio', keys: monthKeys, addSeparator: true},
        {key: 'weekRatio', keys: weekKeys, addSeparator: true},
        {key: 'dayRatio', keys: dayKeys, addSeparator: false}, // 最后一个不加 ''
      ]
      rightValues.forEach((item) => {
        if (!Object.keys(item).length) return
        const yData = []
        const name = item.codeDesc
        ratioConfigs.forEach(({key, keys, addSeparator}) => {
          if (item[key]) {
            const formatted = this.formatTrendRatioData(keys, item[key])
            yData.push(...formatted)
            if (addSeparator) {
              yData.push('');
            }
          }
        })
        tempArr.push({
          name: name,
          type: 'line',
          data: yData,
        })
      })
      let chartColors = lineColors.slice(0, tempArr.length);
      let randomShowLabel = Math.floor(Math.random() * tempArr.length);
      for (let i = 0; i < tempArr.length; i++) {
        tempArr[i].color = chartColors[i]
        tempArr[i].yAxisIndex = 1;
        tempArr[i].label = {
          show: i === randomShowLabel,
          formatter: '{c}%'
        };
      }
      let barData = {
        name: this.genSeriesBarName(this.stage),
        type: "bar",
        label: {},
        itemStyle: {
          color: barColors[0]
        },
        data: [
          ...this.formatTrendData(yearKeys, year),
          "",
          ...this.formatTrendData(quarterKeys, quarter),
          "",
          ...this.formatTrendData(monthKeys, month),
          "",
          ...this.formatTrendData(weekKeys, week),
          "",
          ...this.formatTrendData(dayKeys, day)
        ]
      }
      return {
        grid: {
          top: 80,
          left: 100,
          right: 100,
        },
        title: {
          triggerEvent: true,
          text: `${this.detailData.model} ${chartTit}`,
          left: "center",
          textStyle: {
            color: "#303133"
          }
        },
        legend: {
          show: true,
          top: 36,
          formatter: (name) => {
            return name.length > 12 ? name.substring(0, 12) + '...' : name;
          },
          type: 'scroll',
          tooltip: {
            show: true,
            position: 'bottom',
            extraCssText: 'white-space: pre-wrap;',
            formatter: (params) => {
              return params.name.match(/.{1,100}/g).join('\n')
            }
          }
        },
        tooltip: {
          trigger: "axis",
          show: true,
          axisPointer: {
            type: "cross",
            crossStyle: {
              color: "#999"
            }
          },
          formatter: (params) => {
            return params.map(({seriesType, seriesName, name, marker, value}) => {
              if (name) {
                if (seriesType === "bar") {
                  return `<div style="width: 166px;">
                                            <div style="display: flex">
                                                <div>${marker}Input:</div>
                                                <div style="margin-left: auto">${value}</div>
                                            </div>
                                         </div>`;
                } else {
                  const data = rightValues.find(item => item.codeDesc === seriesName)
                  const keyMap = {
                    Y: "year",
                    Q: "quarter",
                    M: "month",
                    C: "week"
                  };
                  const periodKey = keyMap[name[0]];
                  let ysData;
                  if (Object.keys(keyMap).includes(name[0])) {
                    ysData = data[periodKey][name]
                  } else {
                    ysData = data.day[name]
                  }
                  let ratioStr=!this.isDefectPoint?(`<div style="display: flex">
                                          <div>${marker}不良Ratio:</div>
                                          <div style="margin-left: auto">${value}%</div>
                                        </div>`):''
                  return `<div style="width: 166px;">
                                              <div style="display: flex">
                                               <div>${marker}不良数:</div>
                                               <div style="margin-left: auto">${ysData}</div>
                                             </div>
                                              ${ratioStr}
                                           </div>`
                }
              }
            }).join('')
          }
        },
        xAxis: {
          triggerEvent: true,
          axisTick: {
            show: false
          },
          data: xAxisData,
          axisLabel: {
            interval: 0
          }
        },
        yAxis: [
          {
            type: "value",
            name: "Input",
            nameLocation: "end",
            nameTextStyle: {
              color: "#000"
            },
            nameGap: 30,
            axisLine: {
              show: true
            }
          },
          {
            type: "value",
            name: this.isDefectPoint ? `不良数` : `不良Ratio`,
            nameTextStyle: {
              color: "#000"
            },
            position: "right",
            axisLabel: {
              formatter: value => {
                return this.isDefectPoint === 'DefectPoint' ? value : `${value}`
              }
            },
            nameGap: 30,
            axisLine: {
              show: true
            }
          }
        ],
        series: [barData, ...tempArr]
      }
    },
  },
  created() {
  },
  mounted() {
    //告警详情数据--部门
    this.detailData={"serialCode":"DN CT2024082406D119","model":"55 UHD RGB 0+4","factory":"CT","sourceFactory":"CT","alarmType":"AON"}
    //图表接口数据 http://10.10.181.55/api/alarm/defectRatioTrend?serialCode=DN+CT2024082406D119
    let res={"success":true,"code":0,"message":"业务处理成功","data":[{"day":{"10/31":0,"11/01":0,"11/02":0,"11/03":0,"11/04":0,"11/05":0,"11/06":0},"week":{"CW41":0,"CW42":0,"CW43":0,"CW44":0},"month":{"M9":0,"M10":0,"M11":0},"quarter":{"Q1":0,"Q2":0,"Q3":0,"Q4":0},"year":{"Y24":1412236,"Y25":0},"rightValues":[{"codeDesc":"辉点","day":{"10/31":0,"11/01":0,"11/02":0,"11/03":0,"11/04":0,"11/05":0,"11/06":0},"week":{"CW41":0,"CW42":0,"CW43":0,"CW44":0},"month":{"M9":0,"M10":0,"M11":0},"quarter":{"Q1":0,"Q2":0,"Q3":0,"Q4":0},"year":{"Y24":0,"Y25":0},"dayRatio":{"10/31":0,"11/01":0,"11/02":0,"11/03":0,"11/04":0,"11/05":0,"11/06":0},"weekRatio":{"CW41":0,"CW42":0,"CW43":0,"CW44":0},"monthRatio":{"M9":0,"M10":0,"M11":0},"quarterRatio":{"Q1":0,"Q2":0,"Q3":0,"Q4":0},"yearRatio":{"Y24":0,"Y25":0}}]}]}
    this.trendChart = echarts.init(this.$refs.trendChart);
    let chartTit=this.isDefectPoint?'不良Ratio/不良点位Trend':'不良RatioTrend'
    let option=this.setTrendChartData(res.data[0], chartTit)
    this.trendChart.setOption(option);
  }
}
</script>
<style scoped lang="stylus">
.defect-line-chart {
  width: 100%
  height: 520px
}
</style>